app.controller("companyController", function ($scope, $controller, $location, companyService, uploadService, channelUserService, brandService, taxInfoService) {

    $controller('baseController', {$scope: $scope});

    $scope.searchEntity = {};

    $scope.invoiceServiceDescStr = "";
    $scope.taxInvoiceCategoryList = []
    $scope.arrApp = []
    $scope.isTaxAccount = false
    $scope.isRootAccount = false

    //查询企业列表
    $scope.findPage = function (pageNum, pageSize) {

        if (pageNum == null) pageNum = 1;

        if (pageSize == null) pageSize = 10;

        if (startTime != null) $scope.searchEntity.startTime = startTime;

        if (endTime != null) $scope.searchEntity.endTime = endTime;

        companyService.findPage(pageNum, pageSize, $scope.searchEntity).success(function (response) {

            if (response.code == 200) {

                //获取企业列表
                $scope.companyList = response.data;

                //更新总记录数
                $scope.paginationConf.totalItems = response.total;

            } else {
                alert(response.msg);
            }
        })
    };

    //根据id查询企业
    $scope.findOne = function () {

        var companyId = $location.search()['companyId'];

        if (companyId == null) return;

        companyService.findOne(companyId).success(function (response) {

            if (response.code == 200) {
                $scope.entity = response.data;
                // $scope.findCategoryByTaxInfoId(response.data.taxInfoId)

                for (var i = 0; i < response.data.invoiceServiceDescList.length; i++) {

                    if (i == response.data.invoiceServiceDescList.length - 1) {

                        $scope.invoiceServiceDescStr = $scope.invoiceServiceDescStr + response.data.invoiceServiceDescList[i].serviceName;

                    } else {

                        $scope.invoiceServiceDescStr = $scope.invoiceServiceDescStr + response.data.invoiceServiceDescList[i].serviceName + " ";
                    }


                }

                console.log($scope.invoiceServiceDescStr)
                // 获取当前登录账号信息
                $scope.getLoginUser()
            } else {
                alert(response.msg);
            }
        })


    };

    $scope.getLoginUser = function() {
        var enCodeManagerStr = sessionStorage.getItem("MANAGER");

        //base64解码
        var managerStr = decodeURIComponent(window.atob(enCodeManagerStr));

        var manager = JSON.parse(managerStr);

        $scope.existPhone = $scope.isNull(manager.phone) ? false : true;
        $scope.isTaxAccount = manager.matchValue;
        $scope.loginName = manager.loginName;
        $scope.isRootAccount = manager.loginName === 'root';

    }

    $scope.invoiceServiceDesc = {"id": null, "serviceName": null, "companyId": null};


    //添加或更新
    $scope.insertOrUpdate = function () {


        console.log($scope.isClick);
        if ($scope.isClick) {
            console.log("重复提交");
            return;
        }
        //标记为点击状态
        $scope.isClick = true;

        //参数书否有误
        var isError = false;

        if ($scope.isNull($scope.entity.accountName)) {
            alert("账户名不能为空");
            isError = true;

        }

        if ($scope.isNull($scope.entity.companyName)) {
            alert("公司名不能为空");
            isError = true;

        }

        if ($scope.isNull($scope.entity.subAccount) && $scope.isNull($scope.entity.subAccountForMyBank) && $scope.isNull($scope.entity.alipayAccountBookId)) {
            alert("未创建子账户");
            isError = true;
        }

        if ($scope.entity.serviceRate == null || $scope.entity.serviceRate.length == 0) {
            alert("未设置费率");
            isError = true;
        }


        // if ($scope.entity.recommender == null || $scope.entity.recommender.length == 0){
        //     alert("未设置推荐人");
        //     isError = true;
        // }

        if ($scope.entity.mailInfo == null) {
            alert("未设置开票信息");
            isError = true;
        }

        if ($scope.entity.mailInfo != null) {//开票信息不为空时判断明细

            if ($scope.entity.mailInfo.taxpayerType == null || $scope.entity.mailInfo.taxpayerType.length == 0) {
                alert("未选纳税人类型");
                isError = true;
            }

            if ($scope.entity.mailInfo.companyName == null || $scope.entity.mailInfo.companyName.length == 0) {
                alert("未设置发票抬头");

                isError = true;
            }

            if ($scope.entity.mailInfo.taxpayerIdentifyNumber == null || $scope.entity.mailInfo.taxpayerIdentifyNumber.length == 0) {
                alert("未设置纳税人识别号");
                isError = true;
            }

            if ($scope.entity.mailInfo.addressAndPhone == null || $scope.entity.mailInfo.addressAndPhone.length == 0) {
                alert("未设置单位注册地址及电话");
                isError = true;
            }

            if ($scope.entity.mailInfo.openingBankAndAccount == null || $scope.entity.mailInfo.openingBankAndAccount.length == 0) {
                alert("未设置开户行及账号");
                isError = true;
            }
        }


        if ($scope.invoiceServiceDescStr == null || $scope.invoiceServiceDescStr.length == 0) {
            alert("未设置发票内容");
            isError = true;
        }

        //若渠道不存在赋值默认null
        if ($scope.isNull($scope.entity.channelUserId)) {
            $scope.entity.channelUserId = null;
        }


        if (isError) {//参数错误是还原按钮状态
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }


        var serviceObj;

        if ($scope.invoiceServiceDescStr != null) {//构建 开票内容集合

            $scope.invoiceServiceDescList = [];


            var split = $scope.invoiceServiceDescStr.split(" ");

            console.log($scope.invoiceServiceDescList);

            for (var i = 0; i < split.length; i++) {

                var serverName = split[i];

                var invoiceServiceDesc = JSON.parse(JSON.stringify($scope.invoiceServiceDesc));


                var flag = false;

                var index = null;

                for (var j = 0; j < $scope.entity.invoiceServiceDescList.length; j++) {

                    var invoiceServiceDescParam = $scope.entity.invoiceServiceDescList[j];


                    if (serverName == invoiceServiceDescParam.serviceName) {

                        flag = true;

                        index = j;

                        break;

                    }
                }

                if (flag) {

                    invoiceServiceDesc.id = $scope.entity.invoiceServiceDescList[index].id;

                    invoiceServiceDesc.serviceName = $scope.entity.invoiceServiceDescList[index].serviceName;

                    invoiceServiceDesc.companyId = $scope.entity.invoiceServiceDescList[index].companyId;

                } else {

                    invoiceServiceDesc.id = null;

                    invoiceServiceDesc.serviceName = serverName;

                    invoiceServiceDesc.companyId = null;

                }

                //存入开票内容
                $scope.invoiceServiceDescList.push(invoiceServiceDesc);

            }

            $scope.entity.invoiceServiceDescList = $scope.invoiceServiceDescList;


            $scope.entity.invoiceServiceDescStr = split;
        }

        // return;

        if ($scope.entity.id == null) {//添加账号

            serviceObj = companyService.insert($scope.entity);

        } else {//审核账号

            if ($scope.entity.isCheck == 0 || $scope.entity.isCheck == 3) {
                //运营已审核
                $scope.entity.isCheck = 1;
            }

            serviceObj = companyService.update($scope.entity);

        }

        serviceObj.success(function (response) {

            if (response.code == 200) {

                $scope.entity = {};

                location.href = "company-manage.html"

            } else {
                alert(response.msg);
            }

            //还原按钮初始状态
            $scope.isClick = false;
        }).error(function () {
            //还原按钮初始状态
            $scope.isClick = false;
        })

    };

    //监控是否审核状态
    $scope.$watch("searchEntity.isCheck", function (newValue, oldValue) {

        if (newValue == null)
            return;

        $scope.reloadList();

    });

    //监控签约主体变量 为子账户名赋值
   /* $scope.$watch("entity.signingBody", function (newValue, oldValue) {

        if (newValue == null)
            return;

        $scope.entity.subAccountName = $scope.entity.signingBody;

    });*/

    //监控渠道变量
    $scope.$watch("searchEntity.channelUserId", function (newValue, oldValue) {
        console.log(newValue)
        if (newValue == null)
            return;

        $scope.reloadList();

    });

    //导出功能
    $scope.download = function () {

        if (!confirm("您确定导出吗？可能需要等待...")) return;

        if (startTime != null) $scope.searchEntity.startTime = startTime;

        if (endTime != null) $scope.searchEntity.endTime = endTime;

        companyService.download($scope.searchEntity).success(function (response) {

            if (response.code == 200) {

                // 文件下载
                window.open(response.msg);

                alert("下载完成");
            } else {
                alert(response.msg);
            }
        })
    };

    //重置条件查询记录
    $scope.resetSearchEntity = function () {

        $scope.searchEntity = {};

        $scope.reloadList();
    };

    //企业创建平安子账户
    $scope.createSubAccount = function () {

        console.log($scope.isClick)
        if ($scope.isClick) {
            console.log("重复提交");
            return;
        }

        //标记为点击状态
        $scope.isClick = true;

        if ($scope.entity.signingBody == null || $scope.entity.signingBody.length == 0) {
            alert("未选择代征主体");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        if ($scope.entity.subAccount != null && $scope.entity.subAccount.length != 0) {
            alert("子账号已存在，请勿反复创建");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        companyService.createSubAccount($scope.entity).success(function (response) {

            if (response.code == 200) {

                $scope.entity.subAccount = response.data;
                $scope.entity.subAccountName = $scope.entity.signingBody;

            } else {
                alert(response.msg);
            }

            //还原按钮初始状态
            $scope.isClick = false;

        }).error(function () {
            //还原按钮初始状态
            $scope.isClick = false;
        })
    };

    //查询账户余额
    $scope.findBalance = function () {

        var companyId = $location.search()['companyId'];

        if (companyId == null) return;

        companyService.findBalance(companyId).success(function (response) {

            if (response.code == 200) {

                $scope.balance = response.msg;
            } else {
                // alert(response.msg)
            }
        })


    };


    //修改账号状态
    $scope.modifyAccountStatus = function (status, companyId) {

        var note = "";

        if (status == 2) {
            note = "确定注销该账号吗 ？";
        } else if (status == 1) {
            note = "确认激活账号吗 ？";
        }

        if (!confirm(note))
            return;

        $scope.modifyAccountStatusParam = {"status": null, "companyId": null};

        $scope.modifyAccountStatusParam.status = status;
        $scope.modifyAccountStatusParam.companyId = companyId;

        console.log(JSON.parse(JSON.stringify($scope.modifyAccountStatusParam)));

        companyService.modifyAccountStatus($scope.modifyAccountStatusParam).success(function (response) {

            if (response.code == 200) {

                $scope.reloadList();

                alert(response.msg);
            } else {
                alert(response.msg);
            }
        })

    };


    $scope.uploadParam = {"contractUrl": null, "companyId": null, "businessLicenseUrl": null,"frontIdCard": null,"backIdCard":null};

    $scope.prompt = "仅限 pdf 格式";

    //上传合同
    $scope.uploadContract = function () {

        console.log("合同上传执行");

        uploadService.upload().success(function (response) {

            if (response.code == 200) {

                $scope.uploadParam.contractUrl = response.data;

                $scope.prompt = response.msg;

            } else {
                alert(response.msg);
            }

        });

    };

    //上传合同时添加企业id
    $scope.addCompanyId = function (companyId) {

        $scope.uploadParam.companyId = companyId;
    };


    //添加合同Url
    $scope.addContractUrl = function () {

        if ($scope.uploadParam.contractUrl == null || $scope.uploadParam.contractUrl.length == 0) {
            alert("未上传合同");
            return;
        }

        companyService.addContractUrl($scope.uploadParam).success(function (response) {

            if (response.code == 200) {

                $scope.reloadList();

            } else {

                alert(response.msg);
            }

        });

    };
    $scope.prompt_two = "";
    //上传营业执照
    $scope.uploadBusinessLicense = function () {

        console.log("营业执照上传执行");

        uploadService.uploadBusinessLicense().success(function (response) {

            if (response.code == 200) {

                $scope.uploadParam.businessLicenseUrl = response.data;

                $scope.prompt_two = response.msg;

            } else {
                alert(response.msg);
            }

        });

    };
    //保存营业执照
    $scope.addBusinessLicenseUrl = function () {
        if ($scope.uploadParam.businessLicenseUrl == null || $scope.uploadParam.businessLicenseUrl.length == 0) {
            alert("未上传营业执照");
            return;
        }

        companyService.addBusinessLicenseUrl($scope.uploadParam).success(function (response) {

            if (response.code == 200) {

                $scope.reloadList();

            } else {
                alert(response.msg);
            }

        });
    }


    //获取渠道下拉框集合
    $scope.findChannelUserNames = function () {

        //获取渠道id
        var channelUserId = $location.search()['channelUserId'];


        channelUserService.findChannelUserNames(channelUserId).success(function (response) {

            if (response.code == 200) {

                $scope.channelUserNames = response.data;
            } else {
                alert(response.msg)
            }

        })

    };

    $scope.findBrandList = function () {
        brandService.findAll().success(function (response) {
            if (response.code == 200) {
                $scope.brandList = response.data;
            } else {
                alert(response.msg)
            }
        })
    };

    //获取品牌集合
    $scope.findBrandList = function () {

        brandService.findAll().success(function (response) {

            if (response.code == 200) {
                $scope.brandList = response.data;
            } else {
                alert(response.msg);
            }

        });

    };

    //公司下载当月报税清单
    $scope.downloadTaxList = function () {

        var companyId = $location.search()['companyId'];

        if (companyId == null) {
            alert('参数缺失');
            return;
        }


        companyService.downloadTaxList().success(function (response) {

            if (response.code == 200) {
                window.open(response.msg);
            } else {
                alert(response.msg);
            }
        });
    };

    //根据品牌id获取关联税地信息
    $scope.findTaxInfoByBrandId = function () {

        taxInfoService.findByBrandId().success(function (res) {
            $scope.taxInfoList = res.data;

            angular.forEach($scope.taxInfoList, function (item, index) {
                if (item.isClose === 0) {
                    item.disabled = true;
                }
            });
        });
    };

    $scope.prompt_idCard = "请上传";

    //上传身份证
    $scope.uploadIdCard = function (type) {
        console.log("上传执行")
        $scope.prompt_idCard = "上传中";
        if (type == 1) {
            //正面
            uploadService.uploadFrontIdCard_companyName().success(function (response) {

                if (response.code == 200) {

                    $scope.uploadParam.frontIdCard = response.data;

                    $scope.prompt_idCard = response.msg;

                } else {
                    $scope.prompt_idCard = response.msg;
                    alert(response.msg);
                }

            });
        } else if (type == 2) {
            //反面
            uploadService.uploadBackIdCard_companyName().success(function (response) {

                if (response.code == 200) {

                    $scope.uploadParam.backIdCard = response.data;

                    $scope.prompt_idCard = response.msg;

                } else {
                    $scope.prompt_idCard = response.msg;
                    alert(response.msg);
                }

            });
        }

    };

    //上传身份证时添加公司id
    $scope.addCompanyId = function (companyId) {
        console.log("添加参数执行")
        $scope.uploadParam.companyId = companyId;
    };

    //添加身份证
    $scope.addIdCard = function () {

        if ($scope.isNull($scope.uploadParam.frontIdCard)) {
            alert("未上传身份证正面");
            return;
        }
        if ($scope.isNull($scope.uploadParam.backIdCard)) {
            alert("未上传身份证反面");
            return;
        }

        companyService.addIdCard($scope.uploadParam).success(function (response) {

            if (response.code == 200) {
                $scope.prompt_idCard = "请上传";
                $scope.reloadList();

            } else {

                alert(response.msg);
            }
        });
    };

    /**
     * 创建企业网商子账户
     */
    $scope.createSubAccountForByBank = function () {

        console.log($scope.isClick)
        if ($scope.isClick) {
            console.log("重复提交");
            return;
        }

        //标记为点击状态
        $scope.isClick = true;

        if ($scope.isNull($scope.entity.signingBody)) {
            alert("未选择代征主体");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        if (!$scope.isNull($scope.entity.subAccountForMyBank)) {
            alert("网商子账号已存在，请勿重复创建");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        companyService.createSubAccountForByBank($scope.entity).success(function (response) {

            if (response.code == 200) {

                $scope.entity.subAccountForMyBank = response.data.sub_account_no;
                $scope.entity.subAccountNameForMyBank = $scope.entity.signingBody;
                $scope.entity.uidForMyBank =  response.data.uid;

            } else {
                alert(response.msg);
            }

            //还原按钮初始状态
            $scope.isClick = false;

        }).error(function () {
            //还原按钮初始状态
            $scope.isClick = false;
        })
    };

    //查询网商账户余额
    $scope.findMyBankBalance = function () {

        var companyId = $location.search()['companyId'];

        if (companyId == null) return;

        companyService.findMyBankBalance(companyId).success(function (response) {

            if (response.code == 200) {

                $scope.myBankBalance = response.data;
            }
        })


    };

    /**
     * 接口秘钥下载
     * @param companyId
     */
    $scope.secretKeyDownload = function (companyId) {
        if (!confirm("确认下载此秘钥吗？")) {
            return;
        }
        companyService.secretKeyDownload(companyId).success(function (res) {
            if (res.code == 200) {
                window.open(res.data);
            } else {
                alert(res.msg)
            }
        });
    }

    $scope.contractUrlList = []
    $scope.delParam = {"companyId": null, "contractUrl": null}
    $scope.initContractUrlList = function (companyId, str) {
        $scope.contractUrlList = []
        if (str) {
            $scope.delParam.companyId = companyId
            let arr = str.split("|")
            console.log(arr)
            for (let i = arr.length - 1; i >= 0; i--) {
                console.log(arr[i])
                $scope.contractUrlList.push(arr[i])
            }
        }
    }

    $scope.delContractByUrl = function (index) {
        $scope.delParam.contractUrl = $scope.contractUrlList[index]
        companyService.delContractUrl($scope.delParam).success(function (res) {
            if (res.code == 200) {
                $scope.contractUrlList.splice(index, 1)
            } else {
                alert(res.msg)
            }
        });
    }

    $scope.findCategoryByTaxInfoId = function (taxInfoId) {
        taxInfoService.findInvoiceCategoryByTaxInfoId({ taxInfoId: taxInfoId }).success(function (response) {
            $scope.taxInvoiceCategoryList = response.data
        })
    }

    $scope.checkFirst = function(name) {
        let index = $scope.arrApp.findIndex(ele => {
            return ele === name
        })
        return index > -1
    }

    // 如果需要选中默认值或者带入默认选项需要循环出所以key值添加到数组中
    $scope.categorySelect = function(name){
        let index = $scope.arrApp.indexOf(name);
        if( index < 0 ){
            $scope.arrApp.push(name);
        }else{
            $scope.arrApp.splice(index,1);
        }
        $scope.invoiceServiceDescStr = ""
        for (let i = 0; i < $scope.arrApp.length; i++) {
            $scope.invoiceServiceDescStr  += $scope.arrApp[i] + " | "
        }
    }

    $scope.pinanExist = function() {
        alert('请先点击 "平安账号" 生成子账户')
    }

    $scope.createSubAccountForAlipay = function () {

        console.log($scope.isClick)
        if ($scope.isClick) {
            console.log("重复提交");
            return;
        }

        //标记为点击状态
        $scope.isClick = true;

        if ($scope.isNull($scope.entity.signingBody)) {
            alert("未选择代征主体");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }

        if (!$scope.isNull($scope.entity.alipayAccountBookId)) {
            alert("支付宝资金共管子账号已存在，请勿重复创建");
            //还原按钮初始状态
            $scope.isClick = false;
            return;
        }


        companyService.createSubAccountTogetherFundsAlipay($scope.entity.id, $scope.entity.alipayLogonId, $scope.entity.signingBody).success(function (response) {

            if (response.code == 200) {
                window.open(response.data.signUrl, "_blank")
            } else {
                alert(response.msg);
            }

            //还原按钮初始状态
            $scope.isClick = false;

        }).error(function () {
            //还原按钮初始状态
            $scope.isClick = false;
        })
    };

    //查询网商账户余额
    $scope.findFundsTogetherBalance = function () {

        var companyId = $location.search()['companyId'];

        if (companyId == null) return;

        companyService.queryAccountBookByCompanyId(companyId).success(function (response) {

            if (response.code == 200) {

                $scope.fundsTogetherBalance = response.data;
            }
        })


    };

});